---
import { getCollection } from "astro:content";
import BaseLayout from "@layouts/BaseLayout.astro";
import HeroCard from "@components/HeroCard.astro";
import PostCard from "@components/CommonCard.astro";
import Pagination from "@components/Pagination.astro";
import { SITE_TITLE, SITE_DESCRIPTION } from "@consts";

export async function getStaticPaths() {
  const allPosts = await getCollection("posts");
  allPosts.sort(
    (a, b) =>
      new Date(b.data.pubDate).valueOf() - new Date(a.data.pubDate).valueOf(),
  );

  const firstPagePosts = allPosts.slice(0, 15);
  const remainingPosts = allPosts.slice(15);
  const totalPages = 1 + Math.ceil(remainingPosts.length / 12);

  const paths = [
    {
      params: { page: "1" },
      props: {
        page: {
          data: firstPagePosts,
          currentPage: 1,
          lastPage: totalPages,
        },
      },
    },
  ];

  for (let i = 2; i <= totalPages; i++) {
    const pagePosts = remainingPosts.slice((i - 2) * 12, (i - 1) * 12);
    paths.push({
      params: { page: i.toString() },
      props: {
        page: { data: pagePosts, currentPage: i, lastPage: totalPages },
      },
    });
  }

  return paths;
}

const { page } = Astro.props;
---

<BaseLayout title={SITE_TITLE} description={SITE_DESCRIPTION}>
  {
    page.currentPage === 1 ? (
      <>
        <div class="mb-4 grid grid-cols-1">
          {page.data.length > 0 && <HeroCard post={page.data[0]} />}
        </div>
        <div class="mb-4 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-2">
          {page.data.slice(1, 3).map((post) => (
            <PostCard post={post} />
          ))}
        </div>
        <div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
          {page.data.slice(3).map((post) => (
            <PostCard post={post} />
          ))}
        </div>
      </>
    ) : (
      <div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
        {page.data.map((post) => (
          <PostCard post={post} />
        ))}
      </div>
    )
  }

  <Pagination
    currentPage={page.currentPage}
    lastPage={page.lastPage}
    urlPrev={page.currentPage > 1 ? `/page/${page.currentPage - 1}` : null}
    urlNext={page.currentPage < page.lastPage
      ? `/page/${page.currentPage + 1}`
      : null}
    basePath="/page"
    maxDisplayedPages={5}
  />
</BaseLayout>
